const koaRouter = require('koa-router')
const router = koaRouter()
const jwt = require('jsonwebtoken')
//获取轮播图
router.get('/slides', async(ctx) => {
    try {
        // 解析判断token是否合法
        let token = ctx.request.header.authorization
        console.log(token,111)
        // 对token进行解密
        let decoded = jwt.verify(token, 'haotian')
        console.log(decoded)
        let result = await new Promise((resolve, reject) => {
            connection.query('select * from slides', (err, results) =>{
                if(err) reject(err)
                resolve(results)
            })
        })
        ctx.body = {
            code: 1,
            list: result
        }
    } catch(e) {
        console.log(e)
        ctx.body = {
            code: 0,
            error: e
        }
    }
})

//删除图片
router.post('/deleteUrl',async (ctx)=>{
    try {
        let {id} = ctx.request.body
        console.log(id)
        // 解析判断token是否合法
        let token = ctx.request.header.authorization
        console.log(token,111)
        // 对token进行解密
        let decoded = jwt.verify(token, 'haotian')
        if (decoded && decoded.message) {
            ctx.body = {
                code: 0,
                msg: decoded.message
            }
        }else{
            
            const user = await new Promise((resolve, reject) =>{
                connection.query('select * from workers where phone=?', decoded.phone, (err, results) => {
                    if(err) reject(err)
                    resolve(results)
                })
            })
            if(user[0].workername == 1) {
                // 是管理员
                await new Promise((resolve,reject)=>{
                    connection.query('delete from slides where id=?',[id],(err,res)=>{
                        if(err) reject(err)
                        resolve(res)
                    })
                })
                ctx.body = {
                    code: 1,
                    error: '删除成功'
                }
            } else {
                // 不是管理员
                ctx.body = {
                    code: 0,
                    msg: '此用户无权限删除轮播图'
                }
            }
        }
        
    } catch (error) {
        ctx.body = {
            code: 0,
            error: error
        }
    }
})
exports = router